package test.mywaterfall;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import test.mywaterfall.WaterFall.OnScrollListener;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MyWaterFallActivity extends Activity implements OnScrollListener, OnClickListener {
	private WaterFall waterFall;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        waterFall = (WaterFall) findViewById(R.id.my_waterfall);
        waterFall.setOnScrollListener(this);
        new AsyncImageLoader(waterFall, getAssets()).execute();
    }

	@Override
	public void onTop(int maxCount) {
		Log.d("onTop()", "is called.");
	}

	@Override
	public void onBottom(int maxCount) {
		Log.d("onBottom()", "is called.");
		if (maxCount >= 60) {
			if (!waterFall.hasFooter()) {
				Button button = new Button(this);
				button.setGravity(Gravity.CENTER);
				button.setText("Load More...");
				button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
				waterFall.addFooter(button);
				waterFall.setFooterOnClickListener(this);
			}
		} else {
			if (waterFall.hasFooter()) {
				waterFall.removeFooter().setOnClickListener(null);
			}
			new AsyncImageLoader(waterFall, getAssets()).execute();
		}
	}
	
	@Override
	public void onClick(View v) {
		waterFall.removeAllViews();
		new AsyncImageLoader(waterFall, getAssets()).execute();
	}
	
	public static class AsyncImageLoader extends AsyncTask<Void, Bitmap, Boolean> {
		private static boolean running;
		private WaterFall waterFall;
		private AssetManager am;
		private Random random;
		private List<String> imageFiles;

		public AsyncImageLoader(WaterFall waterFall, AssetManager am) {
			super();
			this.waterFall = waterFall;
			this.am = am;
			try {
				this.imageFiles = Arrays.asList(am.list("images"));
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			this.random = new Random(System.currentTimeMillis());
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			Bitmap bmp = null;
			for (int i = 0; i < 30; i++) {
				try {
					InputStream is = null;
					try {
						is = am.open("images/" + imageFiles.get(random.nextInt(imageFiles.size())), AssetManager.ACCESS_BUFFER);
						bmp = BitmapFactory.decodeStream(is);
						publishProgress(bmp);
					} finally {
						if (is != null) {
							is.close();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!isCancelled()) {
				running = false;
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			if (running) {
				Log.d("ImageLoader is running.", "ignore current task.");
				cancel(true);
			} else {
				running = true;
			}
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Bitmap... bmps) {
			waterFall.addView(bmps[0]);
			super.onProgressUpdate(bmps);
		}
	}
}